package yjj.model.validator;

import yjj.model.annotation.EmailDomain;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Validator;
import java.util.Arrays;

public class EmailDomainValidator implements ConstraintValidator<EmailDomain, String> {

    private String[] allowedDomains;
    private  Validator validator;

    @Override
    public void initialize(EmailDomain constraintAnnotation) {
        this.allowedDomains = constraintAnnotation.allowedDomains();
    }

    @Override
    public boolean isValid(String email, ConstraintValidatorContext context) {
        //context是用来添加错误信息的，这里不需要
        //context.disableDefaultConstraintViolation();作用是禁用默认的错误信息
        if (email == null) {
            return true; // 使用 @NotNull 等注解处理空值
        }
        return Arrays.stream(allowedDomains).anyMatch(email::endsWith);
    }
}